# coding=utf-8
from app.util.http import Response
from django.contrib import auth

def login(request):
    username = request.POST.get('username','')
    password = request.POST.get('password','')

    user = auth.authenticate(username=username, password=password)
    
    dictReturn = {}
    
    #密码错误#
    if user is None:
        dictReturn = {
            'success' : False,
            'action' : Response.ActionType.alert,
            'detail' : '用户名或密码错误！',
        }
    #帐号未激活#
    elif not user.is_active:
        dictReturn = {
            'success' : False,
            'action' : Response.ActionType.alert,
            'detail' : '帐号未启用，请联系管理员！',
        } 
    #登录成功，跳转到default页面#
    else:
        auth.login(request, user)
        lastUrl = request.GET.get('lastUrl','/manager')
        if lastUrl in ('/author/lougout','/author/lougout/',''):
            lastUrl = '/manager'
        dictReturn = {
            'success' : True,
            'action' : Response.ActionType.redirect,
            'detail' : '',
            'url' : lastUrl,
        } 
    return Response.json(dictReturn)

def logout(request):
    auth.logout(request)
    #退出后返回登录页#
    dictReturn = {
        'success' : True,
        'action' : Response.ActionType.redirect,
        'detail' : '',
        'url' : '/author/login',
    } 
    return Response.json(dictReturn)
    
